﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using WMS.Common;
using WMS.InventoryManagement.Differences;
using WMS.Pagination;
using WMS.StorageManagement.BinLocationDefinitions;
using WMS.StorageManagement.DTO;
using WMS.WarehouseManagement.PurchaseDetailss;
using WMS.WarehouseManagement.PurchaseOrders;
using WMS.WarehousingManagement.PurchaseWarehousings.DTO;
using WMS.Web.Controllers.BasicData.Vendors;

namespace WMS.WarehousingManagement.NoticeOfArrivals
{
    /// <summary>
    /// 实现到货通知接口
    /// </summary>
    public class PurchaseWarehousingAppService: IApplicationService, IPurchaseWarehousingAppService
    {
        /// <summary>
        /// 进货商品详情
        /// </summary>
        private readonly IRepository<PurchaseDetails, int> _purchaseDetailsRepository;


        /// <summary>
        ///  进货商品
        /// </summary>
        private readonly IRepository<PurchaseOrder, int> _purchaseOrderRepository;


        /// <summary>
        /// 供应商仓储
        /// </summary>
        private readonly IRepository<Vendor, int> _vendorRepository;

        /// <summary>
        /// 供应商仓储
        /// </summary>
        private readonly IRepository<BinLocationDefinition, int> _binLocationDefinitionRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        public PurchaseWarehousingAppService(IRepository<PurchaseDetails, int> purchaseDetailsRepository, IRepository<PurchaseOrder, int> purchaseOrderRepository, IRepository<Vendor, int> vendorRepository, IRepository<BinLocationDefinition, int> binLocationDefinitionRepository)
        {
            _purchaseDetailsRepository = purchaseDetailsRepository;
            _purchaseOrderRepository = purchaseOrderRepository;
            _vendorRepository = vendorRepository;
            _binLocationDefinitionRepository = binLocationDefinitionRepository;
        }



        /// <summary>
        /// 可用储位
        /// </summary>
        /// <returns></returns>
        public async Task<PagedResult> GetPurchaseWarehousing(int page, int limit)
        {
            /// <summary>
            /// 进货商品
            /// </summary>
            var purchaseDetailsList = await _purchaseDetailsRepository.GetListAsync();

            var bpurchaseDetailsQueryable = purchaseDetailsList.AsQueryable();

            /// <summary>
            ///  进货商品详情
            /// </summary>
            var purchaseOrderList = await _purchaseOrderRepository.GetListAsync();

            var purchaseOrderQueryable = purchaseOrderList.AsQueryable();


            var binLocationDefinition = from a in purchaseOrderQueryable
                                        join b in bpurchaseDetailsQueryable
                                        on a.Id equals b.Pid
                                        select new
                                        {
                                            a.Id,
                                            a.OwnerOfGoods,
                                            a.EstimatedTime,
                                            a.OrderNumber,
                                            a.Transportation,
                                            a.Supplier,
                                            a.ReserveArea,
                                            a.Warehouse,
                                            a.OrderType,
                                            a.AcceptanceTaker,
                                            b.ProductCode,
                                            b.Age,
                                            b.Sdate,
                                            b.CustomerOrderNumber,
                                            b.OrderName,
                                            b.RegistrationAge,
                                            b.NoRegistration,
                                            b.DateTime,
                                            b.batch,
                                            b.PositionOfStorage,
                                            b.Pallet,
                                            b.Unit,
                                            b.Pid,
                                            b.ListingSdate,
                                        };

            var pagedData = binLocationDefinition.Skip((page - 1) * limit).Take(limit);

            // 获取总数
            int totalCount = binLocationDefinition.Count();

            PagedResult pageResult = new PagedResult
            {
                CurrentPage = page,
                PageCount = (int)Math.Ceiling((double)totalCount / limit),
                RowCount = totalCount,
                Queryable = pagedData 
            };

            return await Task.FromResult(pageResult);
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <returns>返回受影响行数</returns>
        public Task<int> AddPurchaseWarehousing(AddDTO add)
        {
            using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    var purchaseOrder = new PurchaseOrder
                    {
                       OwnerOfGoods=add.OwnerOfGoods,
                       EstimatedTime=add.EstimatedTime,
                       OrderNumber=add.OrderNumber,
                       Transportation=add.Transportation,
                       Supplier=add.Supplier,
                       ReserveArea=add.ReserveArea,
                       Warehouse=add.Warehouse,
                       OrderType=add.OrderType,
                       AcceptanceTaker=add.AcceptanceTaker,
                    };


                    var purchaseOrderAdd = _purchaseOrderRepository.InsertAsync(purchaseOrder);

                    var purchaseDetails = _purchaseDetailsRepository.InsertManyAsync(add.PurchaseDetails);

                    transaction.Complete();

                    // 返回受影响的行数
                    // return result;
                    return Task.FromResult(1); // 示例返回值
                }
                catch (Exception ex)
                {
                    // 处理异常
                    Console.WriteLine(ex.Message);
                    // 事务会自动回滚
                    throw;
                }
            }

        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Id">主键Id</param>
        /// <returns>返回受影响行数</returns>
        public Task<int> DeletePurchaseWarehousing(int Id)
        {

            using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    var purchaseOrderAdd = _purchaseOrderRepository.DeleteAsync(Id);

                    var purchaseDetails = _purchaseDetailsRepository.DeleteAsync(m=>m.Pid==Id);

                    transaction.Complete();

                    // 返回受影响的行数
                    return Task.FromResult(1);
                }
                catch (Exception ex)
                {
                    // 处理异常
                    Console.WriteLine(ex.Message);
                    // 事务会自动回滚
                    throw;
                }
            }

          
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <returns></returns>
        public Task<int> UpdatePurchaseWarehousing(UpdateDTO update)
        {
            using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    var purchaseOrder = new PurchaseOrder
                    {
                        OwnerOfGoods = update.OwnerOfGoods,
                        EstimatedTime = update.EstimatedTime,
                        OrderNumber = update.OrderNumber,
                        Transportation = update.Transportation,
                        Supplier = update.Supplier,
                        ReserveArea = update.ReserveArea,
                        Warehouse = update.Warehouse,
                        OrderType = update.OrderType,
                        AcceptanceTaker = update.AcceptanceTaker,
                    };


                    var purchaseOrderAdd = _purchaseOrderRepository.UpdateAsync(purchaseOrder);

                    var purchaseDetails = _purchaseDetailsRepository.UpdateManyAsync(update.PurchaseDetails);

                    transaction.Complete();

                    // 返回受影响的行数
                    // return result;
                    return Task.FromResult(1); // 示例返回值
                }
                catch (Exception ex)
                {
                    // 处理异常
                    Console.WriteLine(ex.Message);
                    // 事务会自动回滚
                    throw;
                }
            }
        }


        /// <summary>
        /// 获取供应商
        /// </summary>
        /// <returns></returns>
        public async Task<List<Vendor>> GetVendor()
        {
            var vendorList =await _vendorRepository.GetListAsync();
            
            return vendorList;
        }


        /// <summary>
        /// 获取仓库信息
        /// </summary>
        /// <returns></returns>
        public async Task<List<BinLocationDefinition>> GetBinLocationDefinition()
        {
            var BinLocationDefinitionList = await _binLocationDefinitionRepository.GetListAsync();
            return BinLocationDefinitionList;
        }
    }
}
